package de.pipeGame;

import de.pipeGame.itemStack.ItemStackHolder;
import de.pipeGame.playingField.PlayingField;
import EventSourcing.BoundButton;
import EventSourcing.BoundListener;
import EventSourcing.EventQueue;
import EventSourcing.PipeDragEvent;
import EventSourcing.TrackableEvent;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;

public class PipeGameActivity extends Activity {

	private final static int HEIGHT_OF_ITEM_IN_PLAYFIELD = 50; // in dp

	private Context context;
	private LinearLayout item_stack;
	private PlayingField playingField;
	ItemStackHolder itemStackHolder;
	Level level;
	EventQueue eventQueue;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		this.context = this.getApplicationContext();

		// get views from the context
		item_stack = (LinearLayout) findViewById(R.id.item_stack);

		eventQueue = new EventQueue();
		
		// initiate the game
		level = GamePreset.getLevel(0);
		itemStackHolder = new ItemStackHolder(context, item_stack, level);

		int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
				HEIGHT_OF_ITEM_IN_PLAYFIELD, getResources().getDisplayMetrics());
		playingField = new PlayingField(context, (ViewGroup) findViewById(R.id.playing_field),
				itemStackHolder, height, height, level, eventQueue);
		
		initButtonBar();
	}

	
	private void initButtonBar(){
		BoundButton undo = new BoundButton ((ImageButton) findViewById(R.id.undo));
		undo.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				undo();
			}
		});
		
		BoundButton reset = new BoundButton((ImageButton) findViewById(R.id.revert_to_start));
		reset.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				while (!eventQueue.pointerIsAtStart()) {
					undo();
				}
			}

		});
		
		BoundButton redo = new BoundButton((ImageButton) findViewById(R.id.redo));
		redo.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				redo();
			}
		});
		
		
		eventQueue.addBoundListener(undo, BoundListener.LOWERBOUND);
		eventQueue.addBoundListener(reset, BoundListener.LOWERBOUND);
		eventQueue.addBoundListener(redo, BoundListener.HIGHERBOUND);
		
	}
	
	private void undo() {
		if (!eventQueue.pointerIsAtStart()){
			TrackableEvent pde = eventQueue.last();
			pde.revertEvent();
			Log.d("PIPEGAME", "undo");
		}
		
	}
	
	private void redo() {
		TrackableEvent pde = eventQueue.next();
		pde.executeEvent();
		Log.d("PIPEGAME", "redo");
		
	}
}